<!-- 字典 -->
<template>
  <div flex-col>
    <!-- 搜索区域 -->

    <div h-75px bd-fff pt-30px pl-20px pr-20px mb-10px flex justify-between items-center>
      <div>
        <el-button
          plain
          text-15px
          type="primary"
          style="
            font-size: 15px;
            color: #fff;
            background: linear-gradient(
              90deg,
              rgba(0, 108, 222, 1) 0%,
              rgba(41, 182, 244, 1) 100%,
              rgba(0, 163, 235, 1) 99%
            );
            border: none;
          "
          @click="handleAddClick()"
        >
          新增字典
        </el-button>
        <el-button type="danger" text-15px :disabled="ids.length === 0" @click="handleDelete()">
          删除
        </el-button>
      </div>
      <div flex items-center>
        <div mr--10px>
          <el-input
            v-model="queryParams.keywords"
            placeholder="字典名称/编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </div>
        <el-button type="primary" text-15px z-2 icon="search" @click="handleQuery">搜索</el-button>
        <el-button
          plain
          text-15px
          icon="refreshRight"
          style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
          @click="handleResetQuery"
        >
          清空
        </el-button>
      </div>
    </div>

    <el-table
      ref="dataTableRef"
      v-loading="loading"
      highlight-current-row
      :data="tableData"
      :header-cell-style="{
        backgroundColor: '#F1F3F7',
        color: '#000',
      }"
      :stripe="true"
      :border="false"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典名称" prop="name" />
      <el-table-column label="字典编码" prop="dictCode" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="220">
        <template #default="scope">
          <el-button type="primary" link size="small" @click.stop="handleOpenDictData(scope.row)">
            <template #icon>
              <Collection />
            </template>
            字典数据
          </el-button>

          <el-button
            type="primary"
            link
            size="small"
            icon="edit"
            @click.stop="handleEditClick(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      ref="paginationRef"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      background
      justify-center
      @pagination="handleQuery"
    />

    <!--字典弹窗-->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :show-close="false"
      :close-on-click-modal="false"
      width="900px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="computedRules" label-width="100px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入字典名称" />
        </el-form-item>

        <el-form-item label="字典编码" prop="dictCode">
          <el-input v-model="formData.dictCode" placeholder="请输入字典编码" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div pt-30px pb-40px flex justify-center>
          <el-button
            plain
            text-14px
            w-98px
            type="primary"
            style="
              font-size: 15px;
              color: #fff;
              background: linear-gradient(
                90deg,
                rgba(0, 108, 222, 1) 0%,
                rgba(41, 182, 244, 1) 100%,
                rgba(0, 163, 235, 1) 99%
              );
              border: none;
            "
            @click="handleSubmitClick"
          >
            提交
          </el-button>
          <el-button w-98px style="margin-left: 55px !important" plain @click="handleCloseDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { debounce } from "lodash-es";
defineOptions({
  name: "Dict",
  inherititems: false,
});

import DictAPI, { DictPageQuery, DictPageVO, DictForm } from "@/api/system/dict.api";

import router from "@/router";

const dataFormRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tableData = ref<DictPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<DictForm>({});

const computedRules = computed(() => {
  const rules: Partial<Record<string, any>> = {
    name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
    dictCode: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
  };
  return rules;
});

// 查询
function handleQuery() {
  loading.value = true;
  DictAPI.getPage(queryParams)
    .then((data) => {
      tableData.value = data.records;
      total.value = Number(data.total);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.keywords = "";
  queryParams.pageNum = 1;
  handleQuery();
}

// 行选择
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 新增字典
function handleAddClick() {
  dialog.visible = true;
  dialog.title = "新增字典";
}

/**
 * 编辑字典
 *
 * @param id 字典ID
 */
function handleEditClick(id: string) {
  dialog.visible = true;
  dialog.title = "修改字典";
  DictAPI.getFormData(id).then((data) => {
    Object.assign(formData, data);
  });
}

// 提交字典表单
function handleSubmitClick() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        DictAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DictAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭字典弹窗
function handleCloseDialog() {
  dialog.visible = false;

  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}
/**
 * 删除字典
 *
 * @param id 字典ID
 */
function handleDelete(id?: number) {
  const attrGroupIds = [id || ids.value].join(",");
  if (!attrGroupIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "确认信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showClose: false,
    confirmButtonClass: "message-box-confirm-button",
    cancelButtonClass: "message-box-cancel-button",
  }).then(
    () => {
      DictAPI.deleteByIds(attrGroupIds).then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开字典项
function handleOpenDictData(row: DictPageVO) {
  router.push({
    path: "/system/dict-data",
    query: { dictCode: row.dictCode, title: "【" + row.name + "】字典数据" },
  });
}

const dataTableRef = ref();
const paginationRef = ref();

// 自适应
const setAdaptive = async () => {
  await nextTick();
  if (!dataTableRef.value) return;
  console.log(dataTableRef.value, "setAdaptive");
  const tableWrapper = dataTableRef.value.$el;
  let offsetBottom = 20;
  let paginationHeight = 0;

  // if (isPlainObject(props.adaptive)) {
  //   offsetBottom = props.adaptive.offsetBottom ?? offsetBottom;
  // }
  paginationHeight = paginationRef.value.$el.offsetHeight;

  tableWrapper.style.height = `${
    window.innerHeight - tableWrapper.getBoundingClientRect().top - offsetBottom - paginationHeight
  }px`;
};

// 防抖
const debounceSetAdaptive = debounce(setAdaptive, 60);

// 挂载
onMounted(() => {
  handleQuery();
  setAdaptive();
  window.addEventListener("resize", debounceSetAdaptive);
});

// 卸载
onBeforeUnmount(() => {
  window.removeEventListener("resize", debounceSetAdaptive);
});
</script>
